package com.softserveinc.lahire.handlers;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;

import com.softserveinc.lahire.builders.HTTPWorker;
import com.softserveinc.lahire.builders.Request;
import com.softserveinc.lahire.builders.ResponseDirector;
import com.softserveinc.lahire.builders.SimpleResponseBuilder;

public class TextHandler implements Handler {
	
	private Handler parent = null;
	public void setParent(Handler parent){
		this.parent = parent;
	}
	public Handler getParent(){
		return parent;
	}

	public void handle (Request request) throws IOException{
		byte[] buffer = null;
		
		if(request.getContentType() != null && request.getContentType().startsWith("text")){
			
			File file = new File(request.getRecoursePath());
				if (file.exists()){
				FileInputStream fis = new FileInputStream(file);
				buffer = new byte[(int) file.length()];
			    fis.read(buffer);
				
				
				SimpleResponseBuilder simpleResponseBuilder = new SimpleResponseBuilder();
				
				HTTPWorker.responseDirector.setResponseBuilder(simpleResponseBuilder);			
				HTTPWorker.responseDirector.constructResponse(buffer, request.getContentType(),HttpURLConnection.HTTP_OK);
				
				}else{
					System.out.println("File cannot be found");
				}
		} else {
			if(parent!=null) parent.handle(request);
		}
		 //return buffer;

	}
}
